/*
 * @(#)JsonStatementPool.java    0.2 02/04/2009
 */
package com.ly.mpayment.persist.catstorage;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ly.mpayment.persist.catstorage.exception.StorageException;

/**
 * Json存储池
 * <p>预定义语句存储池接口的Json实现，使用Json格式在文件中保存预定义语句</p>
 * 
 * @version 0.2
 * @since 0.2
 */
public class JsonStatementPool implements StatementPool {

    /**
     * 读取json文件的工具类
     */
    private Gson gson = new Gson();
    /**
     * 读取字符流对象
     */
    @SuppressWarnings("unused")
	private Reader reader;
    
    private File[] files;
    /**
     * 语句存储池
     */
    private Map<String, String> pool=new HashMap<String,String>();
    /**
     * 日志
     */
    private static Log log = LogFactory.getLog(JsonStatementPool.class);

    public JsonStatementPool(File resourceFile) {
    	if(resourceFile != null){
    		this.files[0] = resourceFile;
    	}
		// try {
		// reader = new FileReader(resourceFile);
		// } catch (FileNotFoundException ex) {
		// log.error("没有找到定义的资源文件", ex);
		// throw new StorageException(ex);
		// }
	}

	public JsonStatementPool(File[] resourceFiles) {
		this.files = resourceFiles;
	}


    @SuppressWarnings("unchecked")
    public void config() {
    	Type type = new TypeToken<HashMap<String, String>>() {
		}.getType();

		try {
			for (File file : files) {
				FileReader reader = new FileReader(file);
				pool.putAll((Map<String, String>) gson.fromJson(reader, type));
				reader.close();
			}

		} catch (IOException ex) {
			log.error("资源文件流不能被关闭", ex);
			throw new StorageException(ex);
		}
    }

    /**
     * 设置语句存储池
     * @param pool 语句存储池
     * @since 0.2
     */
    public void setPool(Map<String, String> pool) {
        this.pool = pool;
    }

    public String get(String key) {
        return pool.get(key);
    }
}
